# -*- coding: utf-8 -*-
# @Time    : 2021/11/06 21:12
# @Author  : XIEHAO
# @Email   : xiehao_1989@126.com
# File     : serializers.py
# @Software: PyCharm
from rest_framework.serializers import ModelSerializer
from school.models import Classes
from users.serializers import UserSerializer
from rest_framework.fields import SerializerMethodField  # 导入序列化器方法字段


class ClassSerializer(ModelSerializer):
    # member = UserSerializer(many=True)  # 序列化器嵌套  在展示班级信息的时候同时展示学生的信息
    memberdetail = SerializerMethodField()
    """
    将memberdetail设置成序列化器方法字段，在班级序列化的时候，自动调用get_memberdetail方法，
    ，将返回的值赋给memberdetail
    """

    class Meta:
        model = Classes
        exclude = ['id', 'is_delete']  # id和逻辑删除不映射

        # 设置过滤信息，将中间表member设置为只写，这样在前端就不会显示
        extra_kwargs = {
            'member': {'write_only': True}
        }

    def get_memberdetail(self, classes):
        # classes.member.all()获取班级中所有成员的信息并进行序列化
        serializer = UserSerializer(classes.member.all(), many=True)
        # 将班级成员按老师和学生进行分类
        # is_staff：是否允许登录后台管理系统
        data = {
            'teacher': [i for i in serializer.data if i['is_staff'] or 1 in i['groups']],
            'student': [i for i in serializer.data if 2 in i['groups']]
        }
        return data
